using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace GameCore.Components
{
    public abstract class UIDragDropHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler
    {
        public Image dragIcon;
        private Vector2 offset;
        protected bool isDragging;
        protected Image dragTemp;

        public virtual void OnBeginDrag(PointerEventData eventData)
        {
            isDragging = IsCanDraggable();
            if (isDragging)
            {
                dragTemp = Instantiate(dragIcon, Global.UI.GetUILayer(1));
                dragTemp.raycastTarget = false;
                dragTemp.transform.SetAsLastSibling();
                dragTemp.transform.position = dragIcon.transform.position;
                dragTemp.rectTransform.GetDragOffset(Global.UI.GetUILayer(1), eventData, out offset);
                dragIcon.color = Color.clear;
                OnCanDrag();
            }
        }

        /// <summary>
        /// 是否可以拖动Item
        /// </summary>
        /// <returns></returns>
        public abstract bool IsCanDraggable();

        public virtual void OnCanDrag() { }

        public virtual void OnDrag(PointerEventData eventData)
        {
            if (isDragging)
            {
                dragTemp.rectTransform.DragUI(Global.UI.GetUILayer(1), eventData, offset);
            }
        }

        public virtual void OnEndDrag(PointerEventData eventData)
        {
            if (isDragging && dragTemp != null)
            {
                isDragging = false;
                dragIcon.color = dragTemp.color;
                DestroyDragTemp();
            }
        }

        internal protected void DestroyDragTemp()
        {
            Destroy(dragTemp.gameObject);
            dragTemp = null;
        }

        public virtual void OnDrop(PointerEventData eventData)
        {
        }
    }

    public abstract class UIDragDropHandler<T> : UIDragDropHandler where T : UIDragDropHandler
    {
        public static T DragItem;

        public override void OnCanDrag()
        {
            DragItem = this as T;
        }

        public override void OnDrop(PointerEventData eventData)
        {
            if (DragItem == this || DragItem == null)
                return;
            OnSwitch(DragItem);
            DragItem.DestroyDragTemp();
            DragItem = null;
        }

        public virtual void OnSwitch(T dragItem)
        {
        }
    }
}